Soy un nuevo desarrollador. Si inicia sesión en nuestro sitio web, se creará JWT. Cuando presiono el botón, tengo que ponerlo en la API como backend. Y si la pantalla tiene éxito, se debe imprimir la dirección en la API. Si falla, debería mostrarse 'fallo de autenticación' en la pantalla. Quiero hacer esto. Por favor, ayúdame.
import axios from 'axios'; import React, { useState } from 'react'; import { Button } from '@material-ui/core'; function TestPage() { const onLogin = () => { var variables = { email: email, password: password, }; Axios.post('/auth/login', variables).then((res) => { setCookie('token', res.payload.accessToken); setCookie('exp', res.payload.accessTokenExpiresIn); Axios.defaults.headers.common['Authorization'] = `Bearer ${res.payload.accessToken}`; Axios.get('/user/me').then((res) => { console.log(res); }); }); }; return ( <> <div> <Button variant="contained" color="primary" style={{ width: '200px' }} onClick={(e) => customFetch(e)}> address </Button> </div> {address && <div>{address}</div>} </> ); } export default TestPage;En general, para cualquier operación de red, es útil saber cuándo está en curso, ha finalizado y/o tiene un error. Configuremos esto:
const [isLoading, setIsLoading] = useState(false) const [data, setData] = useState(null) const [error, setError] = useState(null) // inside your `onLogin` function... setIsLoading(true); Axios.post('/auth/login', variables).then((res) => { setCookie('token', res.payload.accessToken); setCookie('exp', res.payload.accessTokenExpiresIn); Axios.defaults.headers.common['Authorization'] = `Bearer ${res.payload.accessToken}`; // bit messy using the same error state for both but you can always refactor Axios.get('/user/me').then((res) => { console.log(res); setData(res); // not sure where the actual data is with Axios }).catch(err => setError(err); }).catch(err => setError(err)); setIsLoading(false);Durante su POST, establezca las variables de estado en consecuencia:
setIsLoading(true)setData(response.data) // whatever your payload might besetError(error)Ahora, en la devolución de su componente, puede representar condicionalmente sus diferentes estados, por ejemplo:
// your component body if (isLoading) return ( // a loading state ) if (error) return ( // an error state // eg "Authentication Failure" ) return ( // your success/ideal state // eg: <> <div> <Button variant="contained" color="primary" style={{ width: '200px' }} onClick={(e) => customFetch(e)}> address </Button> </div> {address && <div>{address}</div>} </> )Alternativamente, podría aprovechar las variables de forma ligeramente diferente:
return ( <> <div> <Button variant="contained" color="primary" style={{ width: '200px' }} onClick={(e) => customFetch(e)} disabled={isLoading}> address </Button> </div> <div> {isLoading ? 'Checking...' : error !== null ? 'Something went wrong' : 'Ready to submit'} </div> </> )Sin embargo, el estilo ternario puede ser un poco desordenado.